package com.app.util.encrypter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {

	private Charset charset;

	private static final BASE64Encoder encoder = new BASE64Encoder();
	private static final BASE64Decoder decoder = new BASE64Decoder();

	public Base64(String charset) {
		this.charset = Charset.forName(charset);
	}

	public Base64() {
		this.charset = Charset.defaultCharset();
	}

	/**
	 * 编码
	 *  
	 * @param str
	 * @return String
	 * @throws UnsupportedEncodingException
	 */
	public String encode(String str) {
		return encoder.encode(str.getBytes(charset));
	}

	/**
	 * 解码
	 * 
	 * @param str
	 * @return string
	 */
	public String decode(String str) {
		byte[] bt = null;
		try {
			bt = decoder.decodeBuffer(str);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return new String(bt, charset);
	}

}
